package com.corejsf;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.inject.Inject;
import javax.inject.Named; 
import javax.sql.DataSource;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;

@SuppressWarnings("serial")
@Named
@ConversationScoped
/**
 * Login bean. Validates user login, and creates super user for the 
 * system.
 * @author Jitin Dhillon, Kelton Kowalchuk
 *
 */
public class Login implements Serializable {
    /**
     * Used to import the datasource for SQL queries.
     */
	@Resource(mappedName = "java:jboss/datasources/worksheets")
    private static DataSource dataSource;
	/**
	 * Variable to control the lifetime of a user.
	 */
	@Inject private Conversation conversation;
	/**
	 * Brings in the credential bean, which stores all the users.
	 */
	@Inject static Credentials credentials;
    /**
     * Username variable for input box login screen.
     */
    String username;
    /**
     * Password variable for input box login screen.
     */
    String password;
    /**
     * Variable to determine whether the invalid username/password message
     * is displayed.
     */
    private boolean invalid = false;
    /**
     * The user that is currently logged in and using the system.
     */
    private static User activeUser;
    
    /**
     * Default constructor.
     */
    Login() {}

    @PostConstruct
    /**
     * Draws the superUser from the configurations file and creates
     * it in the system if the system is starting up for the first time
     * and there are no users in the system.
     */
    public void instantiate() {
    	//If there are no users in the system, load users from the database.
        if(Credentials.users.size() == 0){
        	PreparedStatement stmt = null;
    		Connection connection = null;
    		try {
    			try {
    				connection = dataSource.getConnection();
    				try {
    					stmt = connection.prepareStatement("SELECT * FROM users");
    					ResultSet rs = stmt.executeQuery();
    					while (rs.next()) {
    						int eNum = rs.getInt("eNumber");
    						String fullName = rs.getString("FullName");
    						String username = rs.getString("UserName");
    						String password = rs.getString("Password");
    						boolean superuser = rs.getBoolean("Superuser");
    						User user = new User(fullName, username, password, eNum);
    						user.setSuperUser(superuser);
    						Credentials.users.add(user);
    						if(eNum >= Credentials.highid){
    							Credentials.highid = eNum + 1;
    						}
    					}
    				} finally {
    					if (stmt != null) {
    						stmt.close();
    					}
    				}
    			} finally {
    				if (connection != null) {
    					connection.close();
    				}
    			}
    		} catch (SQLException ex) {
    			System.out.println("Error in persist ");
    			ex.printStackTrace();
    		}
        }
        
        
    }
    /**
     * Validates the user and password input. Set the user to the currentUser.
     * @return returns navigation to the appropriate page. If superuser logged in
     * return navigation to the user modify page.
     */
    public String validate() {
        System.out.println(username + " " + password);
        for(User u : Credentials.users) {
            if(u.getUsername().equals(username))
                if(u.getPassword().equals(password)) {
                	conversation.begin();
                    if(u.isSuperUser()){
                    	setActiveUser(u);
                    	invalid = false;
                        return "superValid";
                    }else{ 
                    	setActiveUser(u);
                    	invalid = false;
                        return "valid";
                }
            }
        }
        invalid = true;
        return "invalid";
    }
    
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }

    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }
    
    public static User getActiveUser() { return activeUser; }
	public void setActiveUser(User activeUser) { Login.activeUser = activeUser; }

	public Conversation getConversation() { return conversation; }

    public boolean isInvalid() { return invalid; }
    public void setInvalid(boolean invalid) { this.invalid = invalid; }
}